import fs from "fs";
import { sleep } from "../../utils/baseUtils.js";
import {
  clickElement,
  clickImage,
  clickText,
  inputText,
  launchBrowser,
  setDownloadPath,
  waitForNavigation,
  waitForNewPage,
} from "../../utils/puppeteerUtils.js";
import { Page, Browser } from "puppeteer";
import { createInterface } from "readline/promises";
import { SlideOptions } from "./type.js";

const downloadPath = "C:\\Users\\zhen_wang2\\Desktop\\cs-crawler\\crawled-pdf";

const liment = "https://www.bilibili.com";
const token = "https://y.58pic.com/";

main();

async function main() {
  const { browser } = await startBrowser(downloadPath);
  const originalPage = await browser.newPage();
  await originalPage.goto(liment);
  console.log("请手动完成登录操作...");

  // 设置一个监听，检测所需的请求出现
  // 执行mark操作

  const page = await waitForNavigation(originalPage);
  await login(page);
  await mark(browser, page);
}

// ==================浏览器启动配置===================
// 启动浏览器
async function startBrowser(downloadPath: string = "") {
  const { browser, page } = await launchBrowser(downloadPath);
  await setDownloadPath(page, downloadPath);
  return { browser, page };
}

// ==================页面操作函数====================
async function bilibili(browser: Browser, originalPage: Page) {
  const newPagePromise = waitForNewPage(browser);

  await sleep(100, 1000);
  await clickElement(originalPage, ".nav-search-input");
  // 在原页面上进行点击操作以打开新页面
  await sleep(100, 1000);
  // 提示用户输入文本
  const userInput = await getUserInput("请输入要搜索的内容: ");
  await inputText(originalPage, ".nav-search-input", userInput);
  await sleep(100, 1000);
  await clickElement(originalPage, ".nav-search-btn");

  const newPage = await newPagePromise;

  await sleep(100, 1000);

  const imgAltList = await getAllImagesAlt(newPage);
  // for(let i = 0; i < imgAltList.length; i++){
  //   const imgAlt = imgAltList[i];
  //   if(imgAlt){
  //     return;
  //   }
  //   clickImage(newPage, imgAlt,'');
  //   const Page = await newPagePromise;
  //   await sleep(100, 3000);
  //   Page.close();
  // }

  await sleep(100, 3000);
  newPage.close();
  await sleep(100, 1000);
  // 返回原页面实例
  return originalPage;
}

// 获取所有的图片的alt属性
async function getAllImagesAlt(page: Page) {
  console.log("开始点击图片");
  // 选择所有 <img> 元素
  const imgs = await page.$$("img"); // 使用通用的 img 标签选择器

  // 处理所有图像元素，提取其 src 和 alt 属性
  const imgAttributes = await Promise.all(
    imgs.map(async (img) => {
      return await img.evaluate((node) => {
        return {
          alt: node.getAttribute("alt"),
        };
      });
    })
  );

  const imgList = imgAttributes.filter((item) => item.alt);

  console.log("有效的图片列表:", imgList);
  return imgList;
}

// 滑动函数
const scrollPage = async (
  page: Page,
  distance: number = 300,
  time: number = 500
) => {
  while (true) {
    const reachedBottom = await page.evaluate((scrollDistance) => {
      const scrollHeight = document.documentElement.scrollHeight;
      const scrollTop = window.scrollY;
      const windowHeight = window.innerHeight;

      if (scrollTop + windowHeight >= scrollHeight) {
        return true;
      }
      window.scrollTo(0, scrollTop + scrollDistance);
      return false;
    }, distance);

    if (reachedBottom) {
      console.log("Reached the bottom of the page!");
      break;
    }
    await sleep(100, time);
  }
};

// =======================千图网主操作=====================
async function mark(browser: Browser, originalPage: Page) {
  const newPagePromise = waitForNewPage(browser);
  const newPage = await search(originalPage, "小雪");
  // 开启一个for循环，收集所有的图片，然后每个图片在点击过后执行 downloadImg 操作
  await scrollPage(newPage);
  const imgAltList = await getAllImagesAlt(newPage);
  for (let i = 0; i < imgAltList.length; i++) {
    const newPage = await newPagePromise;
    const imgAlt = imgAltList[i].alt;
    if (!imgAlt) {
      return;
    }
    await clickImage(newPage, imgAlt, "");
    await sleep(100, 3000);
    newPage.close();
  }
}

// 千图云设计网站搜索函数
async function search(
  page: Page,
  text: string,
  time: number = 1000
): Promise<Page> {
  await sleep(100, time);
  await clickElement(page, ".input-input");
  await sleep(100, time);
  await inputText(page, ".input-input", text);
  await sleep(100, time);
  await clickElement(page, ".search-button");
  await sleep(100, time);
  const newPage = await waitForNavigation(page);
  return newPage;
}

// 下载图片
async function downloadImg(page: Page) {
  await sleep(100, 1000);
  await clickElement(page, ".downloadBtn");
  await sleep(100, 1000);
  await clickElement(page, "ant-select-selector");
  await sleep(100, 1000);
  await clickElement(page, "ant-select-item-option");
  await sleep(100, 1000);
  await clickElement(page, ".download-btn");
  await sleep(100, 5000);
  page.close();
}

// 搜索对应的标签

// 监听下载事件
// page.on('response', async (response) => {
//   const url = response.url();
//   if (url.endsWith('.pdf')) {
//     console.log(`Detected PDF download: ${url}`);
//     await sleep(3000);  // 等待 3 秒
//     console.log('Closing page after 3 seconds delay.');
//     await page.close();
//     await browser.close();
//   }
// });

// 如输入函数
async function getUserInput(prompt: string) {
  const rl = createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  try {
    // 使用 readline 接口的 promise 方法询问用户
    const userInput = await rl.question(prompt);
    return userInput;
  } finally {
    rl.close();
  }
}

async function login(page: Page) {
  const phoneNumber = await getUserInput("请输入你的手机号: ");
  await page.type("#phone-val-input", phoneNumber);

  const codeInputs = ["#code1", "#code2", "#code3", "#code4"];
  await page.click("#code1");

  // 获取用户输入验证码
  const verificationCode = await getUserInput("请输入你收到的验证码: ");

  for (let i = 0; i < verificationCode.length; i++) {
    const selector = codeInputs[i];
    await page.type(selector, verificationCode[i]);
  }
}

// <input id="phone-val-input"
//         type="text"
//         autocomplete="off"
//         placeholder="请输入你的手机号"
//         value=""
//         onfocus="$(this).parents('.phone-input').addClass('focus')"
//         onblur="$(this).parents('.phone-input').removeClass('focus')">

const time =
  "https://designer-ue.58pic.com/?template_type=1&s_info=e30=&upicId=159129499";

const uuid = "159143874"; // 假设是15秒增加一
